from flask import jsonify, request

resModel = {
    "code": 400,
    "msg": ""
}
books = [
    {
        'id': 1,
        'title': u'论语',
        'auther': u'孔子',
        'price': 18
    },
    {
        'id': 2,
        'title': u'道德经',
        'auther': u'老子',
        'price': 15
    }
]

# books类方法
class BooksController():

    def getBookFilter():
        resModel["code"] = 200
        resModel["data"] = books
        resModel["msg"] = "获取成功"
        return resModel

    def getBookById(id):
        for book in books:
            if book['id'] == id:
                resModel["code"] = 200
                resModel["msg"] = "获取成功"
                resModel["data"] = book
                return (resModel)
        # abort(404)
        resModel["code"] = 400
        resModel["data"] = {}
        resModel["msg"] = "id 错误"
        return (resModel)

    def addBook(params):
        # 输入校验
        print(params)
        if not params or not 'title' in params:
            resModel["code"] = 400
            resModel["data"] = {}
            resModel["msg"] = "title 必填"
            return (resModel)

        book = {
            'id': books[-1]['id'] + 1,
            'title': params['title'],
            'auther': params['auther'],
            'price': params['price'],
        }
        books.append(book)
        print(books)
        resModel["code"] = 200
        resModel["msg"] = "添加成功"
        resModel["data"] = books
        return (resModel)

    def updateBookById(id):
        for book in books:
            if book['id'] == id:
                if request.form and 'title' in request.form:
                    book["title"] = request.form['title']

                if request.form and 'auther' in request.form:
                    book["auther"] = request.form['auther']

                if request.form and 'price' in request.form:
                    book["price"] = request.form['price']

            resModel["code"] = 200
            resModel["msg"] = "修改成功"
            return (resModel)
        resModel["code"] = 400
        resModel["data"] = {}
        resModel["msg"] = "id 错误"
        return (resModel)

    def deleteBookById(id):
        for book in books:
            if book['id'] == id:
                books.remove(book)
                resModel["code"] = 200
                # 测试输出删除后的数据，正式版不输出数据
                resModel["data"] = {}
                resModel["msg"] = "删除成功"
                return (resModel)

        resModel["code"] = 400
        resModel["msg"] = "id 错误"
        return (resModel)
